using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Resoure.Script.Utilities;
using SciptableObject;
using Script.SteerBehaviour;
using Unity.Mathematics;
using UnityEngine;
using EventHandler = Utilities.EventHandler;
using Random = UnityEngine.Random;

public struct EventPoeple
{
    public Coroutine coroutine;
    public MIniPeopleBase peopleItem;
}

public class MiniPeopleManager : Singleton<MiniPeopleManager>
{
    [SerializeField] private GameObject target;
    [SerializeField] private GameObject basePeople;
    private PlayerController controller;
    private Rigidbody2D rb;
    private float currentVelocity;
    public List<MIniPeopleBase> idleMiniPeople;
    public Dictionary<MiniPeopleRequestEvent,EventPoeple> busyMiniPeople;//存储小人和事件协程
    [SerializeField] private SpriteListDataSO skinList;
    private const float BAR_WIDTH = 5.7f;
    
    private void ItemSpeekOnEvent(MiniPeopleRequestEvent item)
    {
        var idlePeople = SelectMiniPeopleInList();
        var iE= StartCoroutine(StartSpeek(item,idlePeople));
        busyMiniPeople.Add(item,new EventPoeple{coroutine = iE,peopleItem = idlePeople});
    }
    IEnumerator StartSpeek(MiniPeopleRequestEvent item,MIniPeopleBase people)
    {
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();

        float elapsed = 0f;
        float duration = item.eventDurationTime;
        people.text.text = item.eventDescribe;
        people.chatBox.SetActive(true);
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float scale = 1 - (elapsed / duration); // 计算缩放比例
            people.bar.GetComponent<SpriteRenderer>().size = new Vector2(BAR_WIDTH*scale,0.15f);
            yield return null; // 等待下一帧
        }
        people.chatBox.SetActive(false);
        people.bar.GetComponent<SpriteRenderer>().size = new Vector2(BAR_WIDTH, 0.15f);
        StopEvent(item);//停止事件
    }

    public void StopEvent(MiniPeopleRequestEvent eventItem)
    {
        if (busyMiniPeople.ContainsKey(eventItem))
        {
            var item = busyMiniPeople[eventItem];
            item.peopleItem.chatBox.SetActive(false);
            item.peopleItem.bar.GetComponent<SpriteRenderer>().size = new Vector2(BAR_WIDTH, 0.15f);
            busyMiniPeople.Remove(eventItem);
            idleMiniPeople.Add(item.peopleItem);
            StopCoroutine(item.coroutine);
        }
    }
    private MIniPeopleBase SelectMiniPeopleInList()
    {
        int count = Random.Range(0, idleMiniPeople.Count);
        var item = idleMiniPeople[count];
        idleMiniPeople.Remove(item);
        return item;
    }
    
    #region 设置Leader的速度

    private void GetValue(GameValues obj)
    {
        //TODO:增减小人 CreateMiniPeople(); 
        var x = obj.numberOfPeople;//人数
        var y = obj.technology > 50 ? obj.technology : 50f;//科技
        var z = obj.faith > 60 ? obj.faith : 60f;//信仰
        currentVelocity = 8* Mathf.Sqrt(Mathf.Sqrt(x)) * Mathf.Log10(y - 40) * Mathf.Log10(z - 50);
        StartCoroutine(SetSpeed());
    }

    IEnumerator SetSpeed()
    {
        var flag = currentVelocity - controller._currentSpeed > 0 ? 1 : -1; // 确定是增加还是减少
        while ((flag > 0 && controller._currentSpeed < currentVelocity) || 
               (flag < 0 && controller._currentSpeed > currentVelocity))
        {
            controller._currentSpeed += 0.1f * flag; // 每次按方向调整速度
            // 防止超过目标值
            if ((flag > 0 && controller._currentSpeed > currentVelocity) || 
                (flag < 0 && controller._currentSpeed < currentVelocity))
            {
                controller._currentSpeed = currentVelocity;
            }
            yield return new WaitForSeconds(0.1f); // 每次调整后的等待时间
        }
    }

    #endregion
    
    protected override void Awake()
    {
        base.Awake();
        controller = target.GetComponent<PlayerController>();
        rb = target.GetComponent<Rigidbody2D>();
        busyMiniPeople = new Dictionary<MiniPeopleRequestEvent, EventPoeple>();
    }

    private void Start()
    {
        CreateMiniPeople();
    }

    public void CreateMiniPeople()
    {
        var pos = target.transform.position;
        pos.y += Random.Range(3,10);
        var mini = Instantiate(basePeople,pos,quaternion.identity);
        RandomSkin(mini);
        var item = mini.GetComponent<MIniPeopleBase>();
        item.StartCoroutine(item.Seek(target));
        idleMiniPeople.Add(item);
        //TODO小人生成逻辑
    }
    public void RemoveMiniPeople()
    {
        int num = Random.Range(0,idleMiniPeople.Count);
        if (idleMiniPeople.Count == 0) return;
        var item = idleMiniPeople[num];
        Destroy(item.gameObject);
        idleMiniPeople.Remove(item);
    }
    private void RandomSkin(GameObject item)
    {
        int num = Random.Range(0, skinList.spriteList.Count);
        var skin = item.GetComponent<SpriteRenderer>();
        skin.sprite = skinList.spriteList[num];
    }
    
    private void OnEnable()
    {
        EventHandler.ValueToUI += GetValue;
        EventHandler.MiniPeopleSpeek += ItemSpeekOnEvent;
    }
    private void OnDisable()
    {
        EventHandler.ValueToUI -= GetValue;
        EventHandler.MiniPeopleSpeek -= ItemSpeekOnEvent;
    }
}
